package com.zyl.blog.service;/**
 * @author 14323
 * @date 2020/8/8 19:53
 */

import com.zyl.blog.dao.TagRepository;
import com.zyl.blog.pojo.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * @Description: TODO
 * @author: scott
 * @date: 2020年08月08日 19:53
 */
@Service
public class TagServiceImpl implements TagService {

    @Autowired
    TagRepository tagRepository;

    @Override
    public Tag saveTag(Tag tag) {
        return tagRepository.save(tag);
    }

    @Override
    public void deleteTag(Long id) {
        tagRepository.deleteById(id);
    }

    @Override
    public Tag updateTag(Long id, Tag tag) {
//        Tag t = tagRepository.findById(id).get();
//        if (t == null){
//            throw new NotFoundException("不存在该标签");
//        }
//        BeanUtils.copyProperties(tag,t);
        return tagRepository.save(tag);
    }

    @Override
    public Tag getTag(Long id) {
        return tagRepository.findById(id).get();
    }

    @Override
    public Tag getTagByName(String name) {
        return tagRepository.findByName(name);
    }

    @Override
    public Page getTagPage(Pageable pageable) {
        return tagRepository.findAll(pageable);
    }

    @Override
    public List<Tag> getAllTags() {
        return tagRepository.findAll();
    }

    @Override
    public List<Tag> getAllTagsSortByBlogNumbers() {
        return null;
    }

    @Override
    public List<Tag> getTopTag(Integer size) {
        Sort sort = Sort.by(Sort.Order.desc("blogs.size"));
        Pageable pageable = PageRequest.of(0, size, sort);
        return tagRepository.findTop(pageable);
    }

    @Override
    public List<Tag> listTag(String ids) {
        return tagRepository.findAllById(convertToIterable(ids));
    }

    public Iterable<Long> convertToIterable(String ids) {//ids:1,2,3
        List<Long> list = new ArrayList<>();
        if (!"".equals(ids) && ids != null){
             String[] idArray = ids.split(",");
            for (int i = 0; i < idArray.length ; i++) {
                list.add(new Long(idArray[i]));
            }
        }
        return list;
    }
}
